package com.addict.applocker.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.addict.applocker.Data.AppListItem;
import com.addict.applocker.R;
import com.addict.applocker.manager.SettingManager;

import java.util.ArrayList;

/**
 * ArrayAdapter不能直接获取控制list，没办法，只能全部自己定义了
 */
public class AppListAdapter extends BaseAdapter {

    protected final Context mContext;
    protected final LayoutInflater mInflater;
    protected ArrayList<AppListItem> mArray = null;

    public AppListAdapter(Context context) { this(context, new ArrayList<AppListItem>()); }
    public AppListAdapter(Context context, ArrayList<AppListItem> array) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(context);
        this.mArray = array;
    }

    public void setItemStart(int position, boolean start) {
        mArray.get(position).setStart(start);
        notifyDataSetChanged();
    }

    public void setItem(int position, AppListItem item) {
        mArray.set(position, item);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mArray.size();
    }

    @Override
    public AppListItem getItem(int position) {
        return mArray.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private static class ViewHolder {
        public FrameLayout mBorder = null;
        public ImageView mAppIcon = null;
        public TextView mAppName = null;
        public TextView mAppPackerName = null;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        if(convertView == null) {
            convertView = mInflater.inflate(R.layout.item_app_list, null);
            vh = new ViewHolder();
            vh.mBorder = (FrameLayout) convertView.findViewById(R.id.bg_border);
            vh.mAppName = (TextView) convertView.findViewById(R.id.tv_app_name);
            vh.mAppPackerName = (TextView) convertView.findViewById(R.id.tv_app_packer);
            vh.mAppIcon = (ImageView) convertView.findViewById(R.id.im_app_icon);
            convertView.setTag(vh);
        }else {
            vh = (ViewHolder) convertView.getTag();
        }

        AppListItem item = getItem(position);
        vh.mAppIcon.setImageDrawable(item.getAppIcon());
        vh.mAppName.setText(item.getAppName());
        vh.mAppPackerName.setText(item.getAppPackageName());

        if (item.isStart()) {
            vh.mBorder.setBackgroundColor(SettingManager.getInstance().getThemeColor());
        }else {
            vh.mBorder.setBackgroundColor(mContext.getResources().getColor(R.color.color_theme_disable));
        }

        return convertView;
    }

}
